package com.dycx.common.rabbitmq;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;

/**
 * 初始化rabbitmq
 *
 * @author Liuhui
 * @since 2023-05-16
 **/
@Configuration
public class InitRabbitMq {

    public InitRabbitMq(RabbitMqConfig rabbitMqConfig,
                        @Qualifier(value = "amqpAdmin") AmqpAdmin amqpAdmin) {
        createPayment(rabbitMqConfig, amqpAdmin);
        createMessage(rabbitMqConfig, amqpAdmin);
    }

    /**
     * 支付
     *
     * @param rabbitMqConfig
     * @param amqpAdmin
     */
    private void createPayment(RabbitMqConfig rabbitMqConfig, AmqpAdmin amqpAdmin) {
        DirectExchange exchange = new DirectExchange(rabbitMqConfig.getPaymentExchange(), true, false);
        amqpAdmin.declareExchange(exchange);

        Queue queue = new Queue(rabbitMqConfig.getPaymentCreateQueue());
        amqpAdmin.declareQueue(queue);
        Binding building = BindingBuilder.bind(queue).to(exchange).with(rabbitMqConfig.getPaymentCreateRouting());
        amqpAdmin.declareBinding(building);
    }

    /**
     * 消息
     *
     * @param rabbitMqConfig
     * @param amqpAdmin
     */
    private void createMessage(RabbitMqConfig rabbitMqConfig, AmqpAdmin amqpAdmin) {
        DirectExchange exchange = new DirectExchange(rabbitMqConfig.getMessageExchange(), true, false);
        amqpAdmin.declareExchange(exchange);

        Queue queue = new Queue(rabbitMqConfig.getMessageCreateQueue());
        amqpAdmin.declareQueue(queue);
        Binding building = BindingBuilder.bind(queue).to(exchange).with(rabbitMqConfig.getMessageCreateRouting());
        amqpAdmin.declareBinding(building);
    }

}
